import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

const http: AxiosInstance = axios.create({
  // baseURL: process.env.VUE_APP_API_PREFIX,
  timeout: 30 * 1000,
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const { data } = response
    const { message, success } = data
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

interface MyConfig extends AxiosRequestConfig {
  url: string
  method: 'GET' | 'POST'
  loading?: false
}

//请求
const request = <T = unknown>(config: MyConfig): Promise<T> => {
  return new Promise((resolve, reject) => {
    http
      .request<T>(config)
      .then((res: AxiosResponse) => {
        resolve(res.data)
      })
      .catch((err: { message: string }) => {
        reject(err)
      })
  })
}

export default request
